<?php

namespace app\model;

use think\Model;
use think\model\relation\HasOne;

class Order extends Model
{
    public function station(): HasOne
    {
        return $this->hasOne(StationBasic::class, "id", "gas_id");
    }

    public function user(): HasOne
    {
        return $this->hasOne(User::class, "id", "account");
    }

    public function confirm(): HasOne
    {
        return $this->hasOne(StationAccount::class, "id", "supplier");
    }

    public function pageData(): array
    {
        $param = request()->param();
        $data = $this->with(['station' => function ($query) {
            $query->with(['mer', 'operation', 'ser', 'brand', 'stationTyp']);
        }, 'confirm', 'user' => function ($query) {
            $query->with(['fromSupplier']);
        }])->when(!empty($param['state']), function ($query) use ($param) {
            $query->where('state', $param['state']);
        })->when(!empty($param['oil_type']), function ($query) use ($param) {
            $query->where('oil_type', $param['oil_type']);
        })->when(!empty($param['order_sn']), function ($query) use ($param) {
            $query->where('order_sn|payment_sn|out_order_sn', $param['order_sn']);
        })->when(!empty($param['create_time']), function ($query) use ($param) {
            $query->where('create_time', 'between', [$param['create_time'][0] . " 00:00:00", $param['create_time'][1] . " 23:59:59"]);
        })->when(!empty($param['mobile']) || !empty($param['code']) || !empty($param['car_number']), function ($query) use ($param) {
            $uid = User::when(!empty($param['mobile']), function ($query) use ($param) {
                $query->where('mobile', $param['mobile']);
            })->when(!empty($param['code']), function ($query) use ($param) {
                $query->where('code', $param['code']);
            })->when(!empty($param['car_number']), function ($query) use ($param) {
                $query->where('car_number', $param['car_number']);
            })->column("id");
            $query->whereIn('account', $uid);
        })->order('create_time desc')->paginate([
            'list_rows' => $param['size'] ?? 30,
            'page' => $param['page'] ?? 1
        ])->toArray();
        return pageData($data);
    }

    public function supplierPage(): array
    {
        $param = request()->param();
//        dd($param);
        $supplier = request()->supplier;
        $data = $this->with(['station' => function ($query) {
            $query->with(['mer', 'operation', 'ser', 'brand', 'stationTyp']);
        }, 'confirm', 'user' => function ($query) {
            $query->with(['fromSupplier']);
        }])->where('sid', $supplier['id'])->when(!empty($param['state']), function ($query) use ($param) {
            $query->where('state', $param['state']);
        })->when(!empty($param['oil_type']), function ($query) use ($param) {
            $query->where('oil_type', $param['oil_type']);
        })->when(!empty($param['order_sn']), function ($query) use ($param) {
            $query->where('order_sn|payment_sn|out_order_sn', $param['order_sn']);
        })->when(!empty($param['create_time']), function ($query) use ($param) {
            $query->where('create_time', 'between', [$param['create_time'][0] . " 00:00:00", $param['create_time'][1] . " 23:59:59"]);
        })->when(!empty($param['mobile']) || !empty($param['code']) || !empty($param['car_number']), function ($query) use ($param) {
            $uid = User::when(!empty($param['mobile']), function ($query) use ($param) {
                $query->where('mobile', $param['mobile']);
            })->when(!empty($param['code']), function ($query) use ($param) {
                $query->where('code', $param['code']);
            })->when(!empty($param['car_number']), function ($query) use ($param) {
                $query->where('car_number', $param['car_number']);
            })->column("id");
            $query->whereIn('account', $uid);
        })->order('create_time desc')->paginate([
            'list_rows' => 30,
            'page' => $param['page'] ?? 1
        ])->toArray();
        return pageData($data);
    }

    public function download($supplier = false): array
    {
        $fn = $supplier ? 'supplierPage' : 'pageData';
        $data = $this->{$fn}();
        $state = [
            1 => '待支付',
            2 => '已支付',
            3 => '已完成',
            4 => '已取消',
            5 => '已退款',
            6 => '退款中',
            7 => '待确认'
        ];
        $result = array_map(function ($items) use ($supplier, $state) {
            if ($supplier)
                return [
                    $items['order_sn'],
                    $items['user']['mobile'] ?? '',
                    $items['user']['car_number'] ?? '',
                    $items['user']['code'] ?? '',
                    $items['station']['name'] ?? '',
                    $items['money'],
                    $items['payment_money'],
                    $items['oil_type'],
                    $items['number'],
                    $state[$items['state']] ?? '',
                    $items['create_time']
                ];
            return [
                $items['station']['name'] ?? '',
                $items['order_sn'],
                $items['money'],
                $items['payment_money'],
                $items['user']['fromSupplier']['name'] ?? '',
                $items['user']['mobile'] ?? '',
                $items['station']['brand']['name'] ?? '',
                $items['station']['operation']['name'] ?? '',
                $items['station']['mer']['name'] ?? '',
                $items['create_time'],
                $state[$items['state']] ?? '',
                $items['confirm']['username'] ?? '',
                $items['confirm_date'] ?? ''
            ];
        }, $data['data']);

        $header = $supplier ? [
            '订单编号',
            '手机号',
            '车牌号',
            '油卡',
            '油站名称',
            '加油金额',
            '扣减金额',
            '加油油品',
            '加油数量',
            '状态',
            '创建时间'
        ] : [
            '油站名称',
            '订单编号',
            '加油金额',
            '扣减金额',
            '供应商名称',
            '手机号',
            '油站品牌',
            '油站经营',
            '商户名称',
            '创建时间',
            '状态',
            '收银员',
            '收银时间'
        ];
        $title = ["加油订单"];
        $file = "加油订单";
        $last_page = $data['last_page'];
        return excel(compact('result', 'header', 'title', 'file', 'last_page'));
    }

    public function refund()
    {
        $param = request()->param();
//        return $this->where('id', $id)->update(['status' => 4]);
        $order = $this->with(['user'])->where('id', $param['id'])->whereIn('state', [2, 3, 7])->find();
        $admin = request()->account;
        $this->startTrans();
        $order->save([
            "refund_time" => date("Y-m-d H:i:s"),
            "state" => 5,
            "remark" => $param['remark'],
            "admin" => $admin['name'] ?? $admin['account']
        ]);
        // 退款
        $balance = $order->user->balance;
        $order->user->inc('balance', $order['amount'])->save();
        //记录动账
        app(UserBalanceDetail::class)->save([
            "uid" => $order['account'],
            "number" => $order['order_sn'],
            "money" => $order['amount'],
            "old_money" => $balance,
            "new_money" => bcadd($balance, $order['amount'], 2),
            "type" => 5,
            "tag" => 1,
            "remark" => $param['remark']
        ]);
        //机构回款
        $suppler = app(Supplier::class)->where('id', $order['user']['supplier'])->find();
        if (!empty($suppler)) {
            $total = bcadd($suppler['balance'], $suppler['forzen_balance'], 2);
            $suppler->dec("account_balance", $order['amount'])->inc("forzen_balance", $order['amount'])->save();
            app(SupplierBalanceNotice::class)->save([
                "sid" => $suppler['id'],
                "money" => $order['amount'],
                "amount" => $total,
                "total" => (float)bcadd($total, $order['amount'], 2),
                "type" => 3,
                "tag" => 1,
                "remark" => "油站退单",
                "order_sn" => $order['order_sn']
            ]);
        }
        //油站回款
        $station = app(StationBasic::class)->where('id', $order['gas_id'])->find();
        if (!empty($station)) {
            $station->inc("balance", $order['money'])->save();
        }
        $this->commit();
        return $order;
    }
}
